package com.black.utils.network.transmit.tcp;

import com.black.utils.commons.network.Sender;
import com.black.utils.commons.pool.PoolProperties;

/**
 * @author ylx
 */
public class TCPSender extends Sender<TCPClient> {
    public TCPSender() {
        this("/tcp.properties");
    }

    public TCPSender(String sourcePath) {
        super(new PoolProperties(sourcePath), TCPClientFactory.class);
    }

    @Override
    public boolean send(String message) {
        int attempts = 1;
        boolean isSend = false;
        // 在尝试次数未达到上限时，尝试获取并使用SFTP客户端发送文件
        while (!isSend && attempts <= properties.getMaxCount()) {
            TCPClient tcpClient = pool.borrowObject();
            if (null != tcpClient) {
                // 尝试将本地文件存储到远程路径
                isSend = tcpClient.send(message);
            }
            // 无论成功或失败，都必须归还SFTP客户端实例到池中
            pool.returnObject(tcpClient);
            attempts++;
        }
        // 如果超过最大尝试次数还未成功，则返回false
        return isSend;
    }
}
